package saxion.frameworkclient;

import java.awt.EventQueue;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;

import sensorframework.client.SensorFrameworkClient;
import sensorframework.client.structuur.DataStruc;
import sensorframework.client.structuur.Sensor;
import sensorframework.client.structuur.Sensors;
import sensorframeworkwebservice.*;
import javax.swing.JTabbedPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.toedter.calendar.JCalendar;
/**
 * The class MainFrame 
 * @author Martijn&Erik
 */
public class MainFrame {

	private JFrame frmClient;
	private ClientWebService SensorFramework;
	private SensorFrameworkClient sensorFrameworkClient;
	private JTable table;
	private JTable table_1;
	private JCalendar jcal;
	
	private String xmlSensorsLocation = "sensors.xml";
	private String xmlSensorLocation = "sensor.xml";
	private String xmlSensorDataLocation = "sensorData.xml";
	
	private Sensors sensors;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame window = new MainFrame();
					window.frmClient.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
	}

	/**
	 * Create the application.
	 */
	public MainFrame() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		
		ClientWebServiceService service = new ClientWebServiceService();
		SensorFramework = service.getClientWebServicePort();
		sensorFrameworkClient = new SensorFrameworkClient();
		
		
		//CREATE GUI
		
		frmClient = new JFrame();
		frmClient.setTitle("Client");
		frmClient.setBounds(100, 100, 598, 546);
		frmClient.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		JPanel panel2 = new JPanel();
		panel2.setLayout(null);
		
		
		jcal = new JCalendar();
		jcal.setLocation(20, 363);
		jcal.setSize(210, 106);
		
		JPanel panel1 = new JPanel();
		panel1.setLayout(null);
		JButton btnHaalDeSensoren = new JButton("Haal de sensoren op");
		
		btnHaalDeSensoren.setLocation(252, 363);
		btnHaalDeSensoren.setSize(160, 23);
		panel1.add(jcal);
		panel1.add(btnHaalDeSensoren);
				
				tabbedPane.add("Sensoren", panel1);
				
				JScrollPane scrollPane = new JScrollPane();
				scrollPane.setBounds(10, 11, 557, 341);
				panel1.add(scrollPane);
				
				table = new JTable();
				scrollPane.setViewportView(table);
				

				JButton btnHaalDeData = new JButton("Haal alle data op van geselecteerde");
				btnHaalDeData.setBounds(252, 397, 229, 23);
				panel1.add(btnHaalDeData);
				
				JButton btnHaalSpecifiekData = new JButton("Haal specifiek data op van geselecteerde");
				btnHaalSpecifiekData.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						
						
						Date date1 = jcal.getDate();
						Timestamp minimum = new Timestamp(date1.getTime());
						System.out.println(date1.getTime());
						Date date2 = new Date();
						Timestamp maximum = new Timestamp(date2.getTime());
						System.out.println(date2.getTime());
						//sensorframeworkwebservice.Timestamp ts = (sensorframeworkwebservice.Timestamp) minimum;
						
						int row = table.getSelectedRow();
		            	int sensorId = (int) table.getModel().getValueAt(row, 0);
		            	Sensor sensor = getSensorFields(sensorId);
		            	
		            	
		            	String[] values = new String[sensor.getDatastructuur().size()-1];
		            	
		            	List<DataStruc> datastrucs = sensor.getDatastructuur();
		            	for(int i =0; i < datastrucs.size()-1; i++ )
		            	{
		            		values[i] = datastrucs.get(i).getName();
		            	}
		            	
		            	Object[][] objects = getSpecificSensorData(sensorId, sensor, minimum, maximum);
		            			
		            	table_1.setModel(new DefaultTableModel(
		            			objects,
		    					values
		    				));
					}
				});
				btnHaalSpecifiekData.setBounds(252, 431, 229, 23);
				panel1.add(btnHaalSpecifiekData);

		tabbedPane.add("Sensor Data", panel2);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(10, 11, 557, 341);
		panel2.add(scrollPane_1);
		
		table_1 = new JTable();
		scrollPane_1.setViewportView(table_1);
		
		frmClient.getContentPane().add(tabbedPane, BorderLayout.CENTER);
		
		
		//Get Senors
		btnHaalDeSensoren.addActionListener(new ActionListener() {
       	 
            public void actionPerformed(ActionEvent e)
            {
            	sensors = getSensors();
            	
            	ArrayList<Sensor> deSensors = sensors.getSensors();
            	
            	Object[][] objects = new Object[deSensors.size()][3];
            	
            	for(int i =0 ; i < deSensors.size(); i++)
            	{
            		Sensor sensor = deSensors.get(i);
            		
            		objects[i][0] = sensor.getId();
            		objects[i][1] = sensor.getName();
            		objects[i][2] = sensor.getDescription();

            	}

            	table.setModel(new DefaultTableModel(
            			objects,
    					new String[] {
    						"ID", "Naam", "Omschrijving"
    					}
    				));
            	
            	table.getColumnModel().getColumn(0).setPreferredWidth(30);
				table.getColumnModel().getColumn(1).setPreferredWidth(104);
				table.getColumnModel().getColumn(2).setPreferredWidth(257);
            }
		});  
		
		
		//get sensor data
		btnHaalDeData.addActionListener(new ActionListener() {
       	 
            public void actionPerformed(ActionEvent e)
            {
            	int row = table.getSelectedRow();
            	int sensorId = (int) table.getModel().getValueAt(row, 0);
            	Sensor sensor = getSensorFields(sensorId);
            	
            	
            	String[] values = new String[sensor.getDatastructuur().size()-1];
            	
            	List<DataStruc> datastrucs = sensor.getDatastructuur();
            	for(int i =0; i < datastrucs.size()-1; i++ )
            	{
            		values[i] = datastrucs.get(i).getName();
            	}
            	
            	Object[][] objects = getSensorData(sensorId, sensor);
            			
            	table_1.setModel(new DefaultTableModel(
            			objects,
    					values
    				));
            }
		});  
	
	}
	
	
	/**
	 * Get sensors from framework
	 * @return sensors
	 */
	public Sensors getSensors() {
		
		
		byte[] data = SensorFramework.getSensors();
		sensorFrameworkClient.saveDataToFile(data, xmlSensorsLocation);
		
		Sensors sensors = sensorFrameworkClient.convertXMLtoSensors(xmlSensorsLocation);
		
		return sensors;

	}
	
	/**
	 * Gen sensor fields
	 * @param sensorId
	 * @return sensor with fields 
	 */
	public Sensor getSensorFields(int sensorId) {
		
		
		byte[] data = SensorFramework.getSensorDataFields(sensorId);
		sensorFrameworkClient.saveDataToFile(data, xmlSensorLocation);
		
		Sensor sensor = sensorFrameworkClient.convertXMLtoSensor(xmlSensorLocation);
		
		return sensor;
		
	}
	
	/**
	 * return sensor values
	 * @param sensorId
	 * @param sensor
	 * @return values
	 */
	public Object[][] getSensorData(int sensorId, Sensor sensor) {
		
		
		byte[] data = SensorFramework.getSensorData(sensorId);
		sensorFrameworkClient.saveDataToFile(data, xmlSensorDataLocation);
		
		File stocks = new File(xmlSensorDataLocation);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        Document doc = null;
		try {
			dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(stocks);
			doc.getDocumentElement().normalize();
		} catch (Exception e) {
			e.printStackTrace();
		}

        // normalize text representation
        doc.getDocumentElement().normalize();
        
        NodeList nodes = doc.getElementsByTagName("sensordata");
        
        Element element = (Element) nodes.item(0);
 
        NodeList rows = element.getElementsByTagName("row");

     
        List<DataStruc> dataStrucs = sensor.getDatastructuur();
        Object[][] objects = new Object[ rows.getLength()][dataStrucs.size()-1];
        
        //values from row
        for(int i =0; i < rows.getLength(); i++)
        {
        	for(int t = 0; t < dataStrucs.size()-1; t++){
        	
        		String value = getValue(dataStrucs.get(t).getName(),(Element) rows.item(i));
        		
        		objects[i][t] = value;
        	}
        }
        
	     return objects;
	}
	
	
	/**
	 * return sensor values
	 * @param sensorId
	 * @param sensor
	 * @return values
	 */
	public Object[][] getSpecificSensorData(int sensorId, Sensor sensor, Timestamp minimum, Timestamp maximum) {
		
//		sensorframeworkwebservice.Timestamp ts1 = new sensorframeworkwebservice.Timestamp();
//		sensorframeworkwebservice.Timestamp ts2 = new sensorframeworkwebservice.Timestamp();
//		ts1.setNanos(minimum.getNanos());
//		ts2.setNanos(maximum.getNanos());
		byte[] data = SensorFramework.getSpecificSensorData(sensorId, minimum.getTime(), maximum.getTime());
		sensorFrameworkClient.saveDataToFile(data, xmlSensorDataLocation);
		
		File stocks = new File(xmlSensorDataLocation);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        Document doc = null;
		try {
			dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(stocks);
			doc.getDocumentElement().normalize();
		} catch (Exception e) {
			e.printStackTrace();
		}

        // normalize text representation
        doc.getDocumentElement().normalize();
        
        NodeList nodes = doc.getElementsByTagName("sensordata");
        
        Element element = (Element) nodes.item(0);
 
        NodeList rows = element.getElementsByTagName("row");

     
        List<DataStruc> dataStrucs = sensor.getDatastructuur();
        Object[][] objects = new Object[ rows.getLength()][dataStrucs.size()-1];
        
        //values from row
        for(int i =0; i < rows.getLength(); i++)
        {
        	for(int t = 0; t < dataStrucs.size()-1; t++){
        	
        		String value = getValue(dataStrucs.get(t).getName(),(Element) rows.item(i));
        		
        		objects[i][t] = value;
        	}
        }
        
	     return objects;
	}
	
	/**
	 * Get value from xml element
	 * @param tag
	 * @param element
	 * @return
	 */
	private static String getValue(String tag, Element element) {
		NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
		Node node = (Node) nodes.item(0);
		return node.getNodeValue();
	}
}
